from . import route_food
from flask import render_template,g,request,jsonify
from models.food.Food import Food
#将FoodCategory 导入进来，因为他和Food绑定了一个relationship
from models.food.FoodCategory import FoodCategory
from models.pay.PayOrderDetail import PayOrderDetail
from models.member.Member import Member
from Service import Pagination,UserService
from app import db,app
from uuid import uuid1
from decimal import Decimal
import os

@route_food.route("/index")
def index():
    current_user = g.current_user
    page_num = int(request.args.get("page", 1))

    # 搜索
    status = int(request.args.get("status", -1))
    cate_id = int(request.args.get("category_id", 0))
    # 保存搜索状态
    condition = {
        "status": status,
        "category_id": cate_id,
    }

    query = Food.query
    if status > -1 and cate_id == 0:
        query = query.filter_by(status=status)
    if status == -1 and cate_id > 0:
        query = query.filter_by(category_id=cate_id)
    if status > -1 and cate_id > 0:
        query = query.filter(Food.status == status,Food.category_id == cate_id)

    # 分页
    totals = query.count()
    pagination = Pagination(page_num, totals)

    if totals != 0:
        data_list = query.offset(pagination["offset"]).limit(pagination["page_size"]).all()
    else:
        data_list = []
    pagination["data_list"] = data_list

    return render_template("food/index.html",current_user=current_user,pagination=pagination,condition=condition)

@route_food.route("/info")
def info():
    current_user = g.current_user
    id = int(request.args.get("id"))
    food = Food.query.get(id)
    if food is None:
        return render_template("error/error.html")

    order_detail = PayOrderDetail.query.filter_by(food_id=id).order_by(PayOrderDetail.created_time.desc()).limit(app.config["SELL_INFO_SIZE"]).all()

    sell_list = []
    for item in order_detail:
        sellInfo = dict()
        sellInfo["member_nickname"] = Member.query.get(item.member_id).nickname
        sellInfo["quantity"] = item.quantity
        sellInfo["price"] = item.price
        sellInfo["created_time"] = item.created_time

        sell_list.append(sellInfo)

    return render_template("food/info.html",current_user=current_user,food=food,sell_list=sell_list)


@route_food.route("/edit",methods=["GET","POST"])
def edit():
    current_user = g.current_user
    id = int(request.args.get("id"))
    food = Food.query.get(id)
    if request.method == "GET":
        food_category_list = FoodCategory.query.filter_by(status=1).all()
        return render_template("food/edit.html", current_user=current_user, food_category_list=food_category_list, food=food)

    resp = {'code': 200, 'msg': '修改成功！', 'data': {}}
    req = request.values
    cate_id = int(req['cate_id']) if 'cate_id' in req else 0
    name = req['name'] if 'name' in req else ''
    price = req['price'] if 'price' in req else ''
    img_path = req['img_path'] if 'img_path' in req else ''
    summary = req['summary'] if 'summary' in req else ''
    stock = int(req['stock']) if 'stock' in req else ''
    tags = req['tags'] if 'tags' in req else ''

    if cate_id < 1:
        resp['code'] = -1
        resp['msg'] = "请选择分类！"
        return jsonify(resp)

    if name is None or len(name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的名称！"
        return jsonify(resp)

    if not price or len(price) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格！"
        return jsonify(resp)

    price = Decimal(price).quantize(Decimal('0.00'))

    if price <= 0:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格！"
        return jsonify(resp)

    if img_path is None or len(img_path) < 15:
        resp['code'] = -1
        resp['msg'] = "请上传封面图！"
        return jsonify(resp)

    main_image = img_path.rsplit("/")[-1]

    if summary is None or len(summary) < 10:
        resp['code'] = -1
        resp['msg'] = "请输入菜品描述，并不能少于10个字符！"
        return jsonify(resp)

    if stock < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的库存量！"
        return jsonify(resp)

    if tags is None or len(tags) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入标签，便于搜索！"
        return jsonify(resp)

    food.category_id = cate_id
    food.name = name
    food.price = price
    food.main_image = main_image
    food.summary = summary
    food.stock = stock
    food.tags = tags
    food.updated_time = UserService.geneTime()
    try:
        db.session.add(food)
        db.session.commit()
    except:
        resp['code'] = -1
        resp['msg'] = "修改失败！"
        return jsonify(resp)

    return jsonify(resp)


@route_food.route("/upload-pic",methods=["POST"])
def uploadPic():
    img_file = request.files.get("pic",None)

    if img_file is None:
        return jsonify({"code":-1,"msg":"上传失败！","src":""})

    # 将图片名按照. 进行切分， 找到最后一个元素，也就是  文件的后缀名
    end_name = img_file.filename.rsplit('.')[-1]

    # 通过文件的后缀名判断 身份为 合法的  图片
    if end_name not in ['jpg', 'png', 'gif', 'jpeg']:
        return jsonify({"code":-1,"msg":"请上传正确的图片文件！","src":""})

    filename = str(uuid1()) + '.' + end_name  # 为了生成一个不重复的文件名

    img_path = app.root_path + "/static/images/food/" + filename   # 将路径和文件名拼接在一起，方便保存文件

    img_file.save(img_path)  # 将图片对象保存到本地

    return jsonify({"code": 200, "msg": "上传成功！", "src": "/static/images/food/" + filename})


@route_food.route("/delete-pic", methods=["POST"])
def deletePic():
    img_path = request.form.get("img_path", None)

    if img_path is None:
        return jsonify({"code": -1, "msg": "删除失败！"})

    root_img_path = app.root_path + img_path
    try:
        os.remove(root_img_path)
    except:
        return jsonify({"code": -1, "msg": "删除失败！"})

    return jsonify({"code": 200, "msg":"删除成功！"})



@route_food.route("/insert",methods=["GET","POST"])
def insert():
    current_user = g.current_user
    if request.method == "GET":
        food_category_list = FoodCategory.query.filter_by(status=1).all()
        return render_template("food/insert.html",current_user=current_user,food_category_list=food_category_list)

    resp = {'code': 200, 'msg': '添加成功！', 'data': {}}
    req = request.values
    cate_id = int(req['cate_id']) if 'cate_id' in req else 0
    name = req['name'] if 'name' in req else ''
    price = req['price'] if 'price' in req else ''
    img_path = req['img_path'] if 'img_path' in req else ''
    summary = req['summary'] if 'summary' in req else ''
    stock = int(req['stock']) if 'stock' in req else ''
    tags = req['tags'] if 'tags' in req else ''

    if cate_id < 1:
        resp['code'] = -1
        resp['msg'] = "请选择分类！"
        return jsonify(resp)

    if name is None or len(name) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的名称！"
        return jsonify(resp)

    if not price or len(price) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格！"
        return jsonify(resp)

    price = Decimal(price).quantize(Decimal('0.00'))

    if price <= 0:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的售卖价格！"
        return jsonify(resp)

    if img_path is None or len(img_path) < 15:
        resp['code'] = -1
        resp['msg'] = "请上传封面图！"
        return jsonify(resp)

    main_image = img_path.rsplit("/")[-1]

    if summary is None or len(summary) < 10:
        resp['code'] = -1
        resp['msg'] = "请输入菜品描述，并不能少于10个字符！"
        return jsonify(resp)

    if stock < 1:
        resp['code'] = -1
        resp['msg'] = "请输入符合规范的库存量！"
        return jsonify(resp)

    if tags is None or len(tags) < 1:
        resp['code'] = -1
        resp['msg'] = "请输入标签，便于搜索！"
        return jsonify(resp)

    food = Food()
    food.category_id = cate_id
    food.name = name
    food.price = price
    food.main_image = main_image
    food.summary = summary
    food.stock = stock
    food.tags = tags
    food.created_time = food.updated_time = UserService.geneTime()
    try:
        db.session.add(food)
        db.session.commit()
    except:
        resp['code'] = -1
        resp['msg'] = "添加失败！"
        return jsonify(resp)

    return jsonify(resp)


@route_food.route("/remove",methods=["POST"])
def remove():
    try:
        id = request.form.get("id")
        Food.query.filter_by(id=id).update({"status": 0})

        db.session.commit()
    except:
        return jsonify({"code":-1,"msg":"删除失败！"})

    return jsonify({"code":200,"msg":"删除成功！"})


@route_food.route("/recover",methods=["POST"])
def recover():
    try:
        id = request.form.get("id")
        food = Food.query.filter_by(id=id).first()
        if food.category.status == 0:
            return jsonify({"code":-1,"msg":"恢复失败,该类别已被删除！"})

        food.status = 1

        db.session.add(food)
        db.session.commit()
    except:
        return jsonify({"code":-1,"msg":"恢复失败！"})

    return jsonify({"code":200,"msg":"恢复成功！"})

